import { editProfile,logout,setupUserProfile} from "./auth.js";
window.editProfile = editProfile;
window.logout = logout;
window.setupUserProfile = setupUserProfile;
// 显示练习题目
export async function displayPracticeQuestions() {
    try {
        // 获取练习编号
        const urlParams = new URLSearchParams(window.location.search);
        const practiceId = urlParams.get('practiceId');
        const username = urlParams.get('username');
        
        if (!practiceId) {
            showError('未提供练习编号');
            return;
        }

        // 显示用户名
        await setupUserProfile(username);
        
        // 调用获取练习题目的接口
        const response = await fetch(`/api/practice/${escapeHTML(practiceId)}/questions`);
        const { data } = await response.json();

        // 合并所有题目并按顺序排序
        const allQuestions = [
    ...(data.choice_questions?.map(q => ({ ...q, type: 'choice' })) || []),
    ...(data.fill_questions?.map(q => ({ ...q, type: 'fill' })) || []),
    ...(data.essay_questions?.map(q => ({ ...q, type: 'essay' })) || [])
].sort((a, b) => a.question_order - b.question_order);

        const questionsContainer = document.getElementById('questionsContainer');
        questionsContainer.innerHTML = '';

        if (allQuestions.length === 0) {
            questionsContainer.innerHTML = `
                <div class="text-center py-8 text-gray-500">
                    <i class="fas fa-inbox text-4xl mb-4 text-gray-300"></i>
                    <p>暂无题目</p>
                </div>
            `;
            return;
        }

        allQuestions.forEach((question, index) => {
            const questionCard = document.createElement('div');
            questionCard.className = 'question-card';
            let content = '';

            switch (question.type) {
                case 'choice':
                    content = `
                <div class="bg-gradient-to-br from-white to-blue-50 rounded-xl border border-blue-100 shadow-md overflow-hidden mb-6">
                    <!-- 标题栏 -->
                    <div class="bg-gradient-to-r from-blue-500 to-blue-600 px-6 py-3">
                        <div class="flex justify-between items-center">
                            <h3 class="text-lg font-bold text-white">选择题</h3>
                            <span class="bg-white text-blue-600 rounded-full px-3 py-1 text-sm font-medium">${escapeHTML(index + 1)}</span>
                        </div>
                    </div>
                    
                    <!-- 内容区 -->
                    <div class="p-6">
                        <div class="text-gray-700 text-lg mb-4 leading-relaxed">
                            ${escapeHTML(question.question)}
                            <span class="question-score text-sm text-gray-500">(${escapeHTML(question.score)}分)</span>
                        </div>
                        
                        <ul class="space-y-3">
                            <li class="option-item flex items-start bg-white/80 p-3 rounded-lg border border-blue-100 cursor-pointer" data-option="A">
                                <input type="radio" name="choice_${escapeHTML(question.question_order)}" value="A" id="choice_${escapeHTML(question.question_order)}_A" class="mt-1 mr-3">
                                <label for="choice_${escapeHTML(question.question_order)}_A" class="flex-1 cursor-pointer">
                                    <span class="bg-blue-100 text-blue-700 font-bold px-3 py-1 rounded mr-3">A</span>
                                    <span>${escapeHTML(question.option_a)}</span>
                                </label>
                            </li>
                            <li class="option-item flex items-start bg-white/80 p-3 rounded-lg border border-blue-100 cursor-pointer" data-option="B">
                                <input type="radio" name="choice_${escapeHTML(question.question_order)}" value="B" id="choice_${escapeHTML(question.question_order)}_B" class="mt-1 mr-3">
                                <label for="choice_${escapeHTML(question.question_order)}_B" class="flex-1 cursor-pointer">
                                    <span class="bg-blue-100 text-blue-700 font-bold px-3 py-1 rounded mr-3">B</span>
                                    <span>${escapeHTML(question.option_b)}</span>
                                </label>
                            </li>
                            ${escapeHTML(question.option_c) ? `
                            <li class="option-item flex items-start bg-white/80 p-3 rounded-lg border border-blue-100 cursor-pointer" data-option="C">
                                <input type="radio" name="choice_${escapeHTML(question.question_order)}" value="C" id="choice_${escapeHTML(question.question_order)}_C" class="mt-1 mr-3">
                                <label for="choice_${escapeHTML(question.question_order)}_C" class="flex-1 cursor-pointer">
                                    <span class="bg-blue-100 text-blue-700 font-bold px-3 py-1 rounded mr-3">C</span>
                                    <span>${escapeHTML(question.option_c)}</span>
                                </label>
                            </li>` : ''}
                            ${escapeHTML(question.option_d) ? `
                            <li class="option-item flex items-start bg-white/80 p-3 rounded-lg border border-blue-100 cursor-pointer" data-option="D">
                                <input type="radio" name="choice_${escapeHTML(question.question_order)}" value="D" id="choice_${escapeHTML(question.question_order)}_D" class="mt-1 mr-3">
                                <label for="choice_${escapeHTML(question.question_order)}_D" class="flex-1 cursor-pointer">
                                    <span class="bg-blue-100 text-blue-700 font-bold px-3 py-1 rounded mr-3">D</span>
                                    <span>${escapeHTML(question.option_d)}</span>
                                </label>
                            </li>` : ''}
                        </ul>
                    </div>
                </div>
                    `;
                    break;
                    case 'fill':
                        const blanks = question.question.match(/__/g) || [];
                        const formattedQuestion = question.question.replace(/__/g, 
                            '<span class="inline-block mx-1 px-3 py-1 bg-green-50 border border-green-200 rounded text-sm">填空</span>'
                        );
                        
                        let blanksInputHtml = '';
                        blanks.forEach((_, i) => {
                            const scoreKey = `blank${escapeHTML(i + 1)}_score`;
                            const score = question[scoreKey] || 0;
                            blanksInputHtml += `
                                <div class="mb-3 flex items-center">
                                    <span class="w-10 text-gray-600">空${escapeHTML(i + 1)}:</span>
                                    <input type="text" class="blank-input ml-2 px-3 py-2 rounded-md bg-green-50 text-gray-700 border border-green-200 focus:ring-2 focus:ring-green-500/50 focus:bg-white" 
                                           placeholder="请输入答案" data-blank="${escapeHTML(i + 1)}">
                                    <span class="text-sm text-gray-500 ml-2">(${escapeHTML(score)}分)</span>
                                </div>
                            `;
                        });
                        
                        content = `
                    <div class="bg-gradient-to-br from-white to-green-50 rounded-xl border border-green-100 shadow-md overflow-hidden mb-6">
                        <div class="bg-gradient-to-r from-green-500 to-green-600 px-6 py-3">
                            <div class="flex justify-between items-center">
                                <h3 class="text-lg font-bold text-white">填空题</h3>
                                <span class="bg-white text-green-600 rounded-full px-3 py-1 text-sm font-medium">${escapeHTML(index + 1)}</span>
                            </div>
                        </div>
                        
                        <div class="p-6">
                            <div class="text-gray-700 text-lg mb-6 leading-relaxed">
                                ${escapeHTML(formattedQuestion)}
                            </div>
                            
                            <div class="answer-section">
                                <div class="answer-label text-gray-600 font-medium mb-3">填空答案：</div>
                                ${escapeHTML(blanksInputHtml)}
                            </div>
                        </div>
                    </div>
                        `;
                        break;
                        case 'essay':
                            content = `
                        <div class="bg-gradient-to-br from-white to-purple-50 rounded-xl border border-purple-100 shadow-md overflow-hidden mb-6">
                            <!-- 标题栏 -->
                            <div class="bg-gradient-to-r from-purple-500 to-purple-600 px-6 py-3">
                                <div class="flex justify-between items-center">
                                    <h3 class="text-lg font-bold text-white">解答题</h3>
                                    <span class="bg-white text-purple-600 rounded-full px-3 py-1 text-sm font-medium">${escapeHTML(index + 1)}</span>
                                </div>
                            </div>
                            
                            <!-- 内容区 -->
                            <div class="p-6">
                                <div class="text-gray-700 text-lg mb-4 leading-relaxed">
                                    ${escapeHTML(question.question)}
                                    <span class="question-score text-sm text-gray-500">(${escapeHTML(question.score)}分)</span>
                                </div>
                                
                                <div class="essay-answer-section">
                                    <div class="answer-label text-gray-600 font-medium mb-3">请作答：</div>
                                    <textarea class="essay-answer w-full h-40 p-4 rounded-lg border border-purple-200 focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 bg-white" 
                                              placeholder="请输入您的解答..."></textarea>
                                </div>
                            </div>
                        </div>
                            `;
                            break;
            }

            questionCard.innerHTML = content;
            questionsContainer.appendChild(questionCard);
            // 添加选项点击事件
            if(question.type === 'choice'){
// 添加选项点击事件（整个选项区域可点击）
const optionItems = questionCard.querySelectorAll('.option-item');
optionItems.forEach(item => {
    item.addEventListener('click', (e) => {
        // 如果点击的是单选按钮本身，不做额外处理
        if (e.target.tagName === 'INPUT') return;
        
        const radioInput = item.querySelector('input[type="radio"]');
        radioInput.checked = true;
        
        // 重置所有选项样式
        optionItems.forEach(opt => {
            opt.classList.remove('bg-blue-200', 'border-blue-500', 'shadow-md');
            opt.classList.add('bg-white/80', 'border-blue-100');
        });
        
        // 设置当前选项为高亮样式
        item.classList.remove('bg-white/80', 'border-blue-100');
        item.classList.add('bg-blue-200', 'border-blue-500', 'shadow-md');
    });
});

// 添加单选按钮点击事件（保持与整个选项区域一致的样式）
const radioInputs = questionCard.querySelectorAll('input[type="radio"]');
radioInputs.forEach(radio => {
    radio.addEventListener('click', (e) => {
        // 找到所属的选项项
        const optionItem = radio.closest('.option-item');
        
        // 重置所有选项样式
        optionItems.forEach(opt => {
            opt.classList.remove('bg-blue-200', 'border-blue-500', 'shadow-md');
            opt.classList.add('bg-white/80', 'border-blue-100');
        });
        
        // 设置当前选项为高亮样式
        optionItem.classList.remove('bg-white/80', 'border-blue-100');
        optionItem.classList.add('bg-blue-200', 'border-blue-500', 'shadow-md');
    });
});}
        });

        disableCopyPaste();
    } catch (error) {
        console.error('加载题目失败:', error);
        showError('加载题目失败，请稍后重试');
    }
}

// 禁用复制粘贴
export function disableCopyPaste() {
    const inputs = document.querySelectorAll('input, textarea');
    inputs.forEach(input => {
        input.addEventListener('copy', e => e.preventDefault());
        input.addEventListener('paste', e => e.preventDefault());
        input.addEventListener('cut', e => e.preventDefault());
        input.addEventListener('contextmenu', e => e.preventDefault());
        input.classList.add('no-copy');
    });
}

// 显示错误信息
export function showError(message) {
    const questionsContainer = document.getElementById('questionsContainer');
    questionsContainer.innerHTML = `
        <div class="error-message">
            <h3><i class="fas fa-exclamation-circle mr-2"></i>加载失败</h3>
            <p>${escapeHTML(message)}</p>
        </div>
    `;
}

// 提交练习
document.getElementById('submitPracticeBtn').addEventListener('click', async () => {
    const urlParams = new URLSearchParams(window.location.search);
    const practiceId = urlParams.get('practiceId');
    const username = urlParams.get('username');
    
    if (!practiceId || !username) {
        showError('缺少必要参数');
        return;
    }

    // 获取用户ID
    const userResponse = await fetch(`/user-info?username=${escapeHTML(username)}`);
    const userData = await userResponse.json();
    const userId = userData.user_id;
    
    // 检查截止时间
    const practiceDetailResponse = await fetch(`/practice/detail/${escapeHTML(practiceId)}?userId=${escapeHTML(userId)}`);
    const practiceDetail = await practiceDetailResponse.json();    
    const deadline = new Date(practiceDetail.deadline);    
    const now = new Date();
    
    if (now > deadline) {        
        showError('已超过练习截止时间，无法提交。');        
        return;
    }

    // 检查未作答题目
    const allQuestions = document.querySelectorAll('.question-card');
    let hasUnanswered = false;
    let errorMessage = '<h3><i class="fas fa-exclamation-triangle mr-2"></i>以下题目未完成：</h3><ul>';
    
    allQuestions.forEach((questionCard, index) => {        
        const questionType = questionCard.querySelector('ul') ? 'choice' : 
                           questionCard.querySelector('textarea') ? 'essay' : 'fill';
        
        switch (questionType) {            
            case 'choice':                
                const choices = questionCard.querySelectorAll('input[type="radio"]');                
                const isChoiceAnswered = Array.from(choices).some(choice => choice.checked);                
                if (!isChoiceAnswered) {                    
                    hasUnanswered = true;                    
                    errorMessage += `<li>第 ${escapeHTML(index + 1)} 题（选择题）未选择答案</li>`;
                }                
                break;            
            case 'fill':                
                const fillInputs = questionCard.querySelectorAll('input[type="text"]');                
                fillInputs.forEach((input, i) => {                    
                    if (input.value?.trim() === '') {                        
                        hasUnanswered = true;                        
                        errorMessage += `<li>第 ${escapeHTML(index + 1)} 题（填空题）空 ${escapeHTML(i + 1)} 未填写</li>`;
                    }
                });                
                break;            
            case 'essay':                
                const essayTextarea = questionCard.querySelector('textarea');                
                if (essayTextarea.value?.trim() === '') {                    
                    hasUnanswered = true;                    
                    errorMessage += `<li>第 ${escapeHTML(index + 1)} 题（解答题）未填写答案</li>`;
                }                
                break;
        }
    });
    
    errorMessage += '</ul>';
    
    if (hasUnanswered) {
        const errorDiv = document.createElement('div');
        errorDiv.className = 'error-message';
        errorDiv.innerHTML = errorMessage;
        questionsContainer.prepend(errorDiv);
        window.scrollTo({ top: 0, behavior: 'smooth' });
        return;
    }

    // 提交答案
    try {
        for (const [index, questionCard] of Array.from(allQuestions).entries()) {            
            const questionType = questionCard.querySelector('ul') ? 'choice' : 
                               questionCard.querySelector('textarea') ? 'essay' : 'fill';
            const questionOrder = index;
            
            if (questionType === 'choice') {
                const selectedOption = questionCard.querySelector('input[type="radio"]:checked');
                const userAnswer = selectedOption ? selectedOption.value : '';
                
                const response = await fetch('/submit-choice-answer', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ practiceId, questionOrder, userId, userAnswer })
                });
                
                const data = await response.json();
                if (!data.success) {
                    throw new Error(`提交第 ${escapeHTML(questionOrder+1)} 题失败: ${escapeHTML(data.message)}`);
                }
            } else if (questionType === 'fill') {
                const fillInputs = questionCard.querySelectorAll('input[type="text"]');
                const userAnswers = Array.from(fillInputs).map(input => input.value.trim() || null);
                
                for(const userAnswer of userAnswers){
                    if(userAnswer.length>200){
                        alert('答案不能超过200字');
                        return;
                    }
                }
                const response = await fetch('/submit-fill-answer', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ practiceId, questionOrder, userId, answers: userAnswers })
                });
                
                const data = await response.json();
                if (!data.success) {
                    throw new Error(`提交第 ${escapeHTML(questionOrder+1)} 题失败: ${escapeHTML(data.message)}`);
                }
            } else if (questionType === 'essay') {
                const essayTextarea = questionCard.querySelector('textarea');
                const userAnswer = essayTextarea.value.trim();

               if(userAnswer.length>200){
                        alert('答案不能超过200字');
                        return;
                    }
                
                const response = await fetch('/submit-essay-answer', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ practiceId, questionOrder, userId, answer: userAnswer })
                });
                
                const data = await response.json();
                if (!data.success) {
                    throw new Error(`提交第 ${escapeHTML(questionOrder+1)} 题失败: ${escapeHTML(data.message)}`);
                }
            }
        }

        // 提交练习本身
        const submitPracticeResponse = await fetch('/submit-practice', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ practice_id: practiceId, user_id: userId })
        });
        
        const submitPracticeData = await submitPracticeResponse.json();
        if (!submitPracticeResponse.ok) {
            throw new Error(submitPracticeData.message);
        }

        alert('提交练习成功！');
        window.location.href = 'todo-practice.html' + window.location.search;
    } catch (error) {
        console.error('提交练习失败:', error);
        showError('提交练习失败: ' + error.message);
    }
});

// 返回按钮
document.getElementById('goBackBtn').addEventListener('click', () => {
    window.history.back();
});

// 页面加载完成后显示题目
document.addEventListener('DOMContentLoaded', displayPracticeQuestions);

document.addEventListener('DOMContentLoaded', function() {
    // 获取"返回"链接元素
    const backLink = document.querySelector('ul.flex li:first-child a');
    if (backLink) {
        // 添加点击事件监听器
        backLink.addEventListener('click', function(event) {
            event.preventDefault(); 
            window.location.href ='todo-practice.html'+window.location.search;
        });
    }
});

export function escapeHTML(str) {
    if (typeof str !== 'string') return str;
    return str.replace(/[&<>"']/g, function (match) {
    switch (match) {
    case '&':
    return '&amp;';
    case '<':
    return '&lt;';
    case '>':
    return '&gt;';
    case '"':
    return '&quot;';
    case "'":
    return '&#039;';
}
 });
}